package com.permission.service.impl;

import com.permission.dao.PerDeptDao;
import com.permission.dao.PerUserDao;
import com.permission.model.PerDept;
import com.permission.model.PerUser;
import com.permission.service.PerDeptService;
import com.solution.framework.service.impl.BaseServiceImpl;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with generator tools.
 * User: sunguangzhu
 * DateTime:2014-05-07 12:48:37
 */
@Service
public class PerDeptServiceImpl extends BaseServiceImpl<PerDept> implements PerDeptService {
    @Resource
    private PerDeptDao perDeptDao;

    @Resource
    private PerUserDao perUserDao;

    @Override
    @Transactional
    public void deleteMoreCascade(Long id) {
        List<Criterion> criterions = new ArrayList<Criterion>();
        criterions.add(Restrictions.eq("parent.id", id));
        List<PerDept> perDepts = this.perDeptDao.listByCriteria(criterions);
        this.deleteMoreCascade(perDepts);

        criterions.clear();
        criterions.add(Restrictions.eq("perDept.id", id));
        List<PerUser> perUsers = perUserDao.listByCriteria(criterions);
        for (PerUser perUser : perUsers) {
            this.perUserDao.delete(perUser);
        }
        this.perDeptDao.delete(id);
        //To change body of implemented methods use File | Settings | File Templates.
    }

    @Transactional
    private void deleteMoreCascade(List<PerDept> perDepts) {
        for (PerDept perDept : perDepts) {
            List<Criterion> criterions = new ArrayList<Criterion>();
            criterions.add(Restrictions.eq("parent.id", perDept.getId()));
            List<PerDept> perDeptList = this.perDeptDao.listByCriteria(criterions);
            if (perDeptList != null && perDeptList.size() > 0) {
                this.deleteMoreCascade(perDeptList);
            } else {
                criterions.clear();
                criterions.add(Restrictions.eq("perDept.id", perDept.getId()));
                List<PerUser> perUsers = perUserDao.listByCriteria(criterions);
                for (PerUser perUser : perUsers) {
                    this.perUserDao.delete(perUser);
                }
                this.perDeptDao.delete(perDept);
            }
        }
    }
}

